
// 用于拼接字符串（自动插入换行）并替换到代码文件的类
function myString(dfText) {
  this.val = dfText || ''
  this.add = text => (this.val += (text || '') + '\r\n')
  this.writeTo = (strCode,tag) => {
      return strCode.replace(new RegExp(`\\$\\$${tag},?`, 'g'), this.val.trimLeft())
  }
}


export const generatorAppSingle = (setting,temp)=>{
  let strCode = temp
  temp = null
  const formInfo = window.$deepClone(setting.formInfo)
  const page = setting.page
  const dbTable = setting.dbTable
  const gridtables = {}

  // 获取表单字段
  const componentMap = {}
  const upCtrls = []
  const viewTables = []
  formInfo.tabList.forEach(tab=>{
    tab.components.forEach(component =>{
      let className
      if(component.table){
        const table = dbTable.find(t=>t.name == component.table) || {}
        className = table.className || ''
      }

      if(!['gridtable','divider','btn','card','viewtable'].includes(component.type)){
        componentMap[component.prop] =component
        component.prop =  `${window.$lowerFirst(className)}Entity_${window.$lowerFirst(component.field)}`
        component.table = `${window.$lowerFirst(className)}Entity`
        if(component.upCtrl){
          upCtrls.push(component)
        }
      }
      else if(['gridtable'].includes(component.type)){
        gridtables[component.table] = true
        component.prop = `${window.$lowerFirst(className)}List`
        component.table = `${window.$lowerFirst(className)}List`
       
        component.children.forEach(ccomponent=>{
          componentMap[ccomponent.prop] =ccomponent
          if(ccomponent.upCtrl){
            upCtrls.push(ccomponent)
          }
          ccomponent.prop = ccomponent.field
          delete ccomponent.table
          delete ccomponent.csType
          delete component.span
          delete component.subfield
          
        })
      }
      else if(['viewtable'].includes(component.type)){
        viewTables.push(component)
      }

      delete component.changeDataEvent
      delete component.isDESC
      delete component.span
      delete component.csType
    })
  })

  upCtrls.forEach(item=>{
    if(componentMap[item.upCtrl]){
      item.upCtrl = componentMap[item.upCtrl].prop
    }
  })
  viewTables.forEach(item=>{
    if(componentMap[item.paramFiled]){
      item.paramFiled = componentMap[item.paramFiled].prop
    }
  })

  let FORMSCHEME = new myString()
  delete formInfo.afterSaveEvent
  delete formInfo.afterValidateForm
  delete formInfo.beforeSetData
  delete formInfo.changeDataEvent
  delete formInfo.dialogHeight
  delete formInfo.dialogWidth
  delete formInfo.drawerWidth
  delete formInfo.gutter
  delete formInfo.historyType
  delete formInfo.openType
  delete formInfo.size
  
  FORMSCHEME.add(JSON.stringify(formInfo))
  strCode = FORMSCHEME.writeTo(strCode,'FORMSCHEME')
  FORMSCHEME = null


  let DELETEBTN = new myString()
  let HANDLEDELETE = new myString()
  page.btns.forEach(t=>{
    if(t.prop == 'Delete'){
      DELETEBTN.add(`			<button v-if="mode !== 'create' && editMode && GET_BUTTON_AUTH('Delete',moduleId)" @click="handleDelete" type="warn">删除</button>`)
      
      HANDLEDELETE.add(`			async handleDelete() {`)
      HANDLEDELETE.add(`				if (!(await this.CONFIRM('删除项目', '确定要删除该项吗？', true))) {`)
      HANDLEDELETE.add(`					return`)
      HANDLEDELETE.add(`				}`)
      HANDLEDELETE.add(`				this.LOADING('提交删除中…')`)
      HANDLEDELETE.add(`				const success =  await this.HTTP_DELETE({url: "/${window.$lowerFirst(setting.moduleId)}/${window.$lowerFirst(setting.name)}/"+ this.keyValue, errorTips: '删除失败'})`)
      HANDLEDELETE.add('				this.HIDE_LOADING()')
      HANDLEDELETE.add(`				if (success) {`)
      HANDLEDELETE.add('					this.EMIT(`custom-list-change-${this.moduleId}`)')
      HANDLEDELETE.add(`					this.NAV_BACK()`)
      HANDLEDELETE.add("					this.TOAST('删除成功', 'success')")
      HANDLEDELETE.add(`				}`)
      HANDLEDELETE.add(`			},`)
    }
  })
  strCode = DELETEBTN.writeTo(strCode,'DELETEBTN')
  DELETEBTN = null

  strCode = HANDLEDELETE.writeTo(strCode,'HANDLEDELETE')
  HANDLEDELETE = null

  // 
  let LOADFORM = new myString()
  let GETFORM = new myString()

  if(dbTable.length == 1){
    LOADFORM.add(`                const formData = {${window.$lowerFirst(dbTable[0].className)}Entity:_formData}`)
    GETFORM.add(`                const postData = this.GET_FORMDATA(_postData,'${window.$lowerFirst(dbTable[0].className)}Entity')`)
  }
  else{
    LOADFORM.add(`                const formData = _formData`)
    GETFORM.add(`                const postData= {}`)
    dbTable.forEach(table=>{
      if(gridtables[table.name]){
        GETFORM.add(`                postData.${window.$lowerFirst(table.className)}List = _postData.${window.$lowerFirst(table.className)}List`)
        
      }
      else{
        GETFORM.add(`                postData.${window.$lowerFirst(table.className)}Entity = this.GET_FORMDATA(_postData,'${window.$lowerFirst(dbTable[0].className)}Entity')`)
      }
    })  
  }

  strCode = LOADFORM.writeTo(strCode,'LOADFORM')
  LOADFORM = null

  strCode = GETFORM.writeTo(strCode,'GETFORM')
  GETFORM = null


  // 数据请求
  strCode = strCode.replace(new RegExp(`\\$\\$URL?`, 'g'),`/${window.$lowerFirst(setting.moduleId)}/${window.$lowerFirst(setting.name)}`)
 
  return strCode
}

